//
//  HR_BLELinkViewController.m
//  Pods
//
//  Created by xiaoming on 17/07/28.
//
//

#import "HR_BLELinkViewController.h"
#import "HR_BLELinkView.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "HR_BLELinkConstant.h"
#import "HR_BLELinkManager.h"
#import "HR_BLELinkInfoModel.h"

/** 外设前缀(**************** 需要替换 ****************) */
static NSString *const PERIPHERAL_PREFIX = @"FS";
/** linkView set alpha duration */
static CGFloat const DURATION_LINKVIEW_ALPHA = .2f;

@interface HR_BLELinkViewController ()<CBCentralManagerDelegate, BlueToothLinkDelegate>

/** 蓝牙连接 tableView */
@property (strong, nonatomic) HR_BLELinkView *linkView;
/** 外设 manager */
@property (nonatomic, strong) CBCentralManager *centralManager;
/** Blue tooth link manager */
@property (strong, nonatomic) HR_BLELinkManager *BLEManager;
/** 记录当前连接外设 uuid.identifier */
@property (strong, nonatomic) NSUUID *peripheralIdentifier;
/** 设备 */
@property (nonatomic, strong) NSMutableArray<CBPeripheral *> *devicesMArr;
/** 连接成功的外设 */
@property (nonatomic, strong) CBPeripheral *peripheral;
/** 若已退出则蓝牙不需要再重新连接 */
@property (assign, nonatomic) BOOL isDismiss;

@end

@implementation HR_BLELinkViewController

#pragma mark - ---------- 生命周期 ----------

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeData];
    [self configUI];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    self.isDismiss = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - ---------- 私有方法 ----------

#pragma mark 数据初始化
- (void)initializeData {
    [self setUpCentralManager];
}

- (void)setUpCentralManager {
    self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil options:nil];
}

#pragma mark UI布局
- (void)configUI {
    self.view.backgroundColor = [UIColor whiteColor];
    [self addBLELinkView];
}

- (void)addBLELinkView {
    HR_BLELinkView *linkView = [[[NSBundle bundleForClass:[HR_BLELinkView class]] loadNibNamed:NSStringFromClass([HR_BLELinkView class]) owner:self options:nil] firstObject];
    [self.view addSubview:linkView];
    self.linkView = linkView;
    [linkView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_offset(UIEdgeInsetsZero);
    }];
    WEAK(weakSelf);
    linkView.cancelBlock = ^{
        //取消
        STRONG(strongSelf, weakSelf);
        [weakSelf dismissViewControllerAnimated:YES completion:^{
            [strongSelf clearData];
        }];
    };
    linkView.selectPrepheralBlock = ^(NSUUID *peripheralIdentifier){
        //点击连接外设
        weakSelf.peripheralIdentifier = peripheralIdentifier;
        [weakSelf connectPeripheralWithPeripheralIdentifier:peripheralIdentifier];
    };
}

#pragma mark 开始连接
- (void)connectPeripheralWithPeripheralIdentifier:(NSUUID *)peripheralIdentifier {
    WEAK(weakSelf);
    [self.devicesMArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        CBPeripheral *peripheral = obj;
        if ([peripheralIdentifier isEqual:peripheral.identifier]) {
            [weakSelf.linkView indicatorAnimating:YES peripheral:peripheral];
            [self.centralManager connectPeripheral:peripheral options:nil];
            *stop = YES;
        }
    }];
}

#pragma mark - 蓝牙管理
- (void)configPeripheral {
    self.BLEManager = [[HR_BLELinkManager alloc] initWithPrepheral:self.peripheral];
    self.BLEManager.delegate = self;
    self.peripheral.delegate = self.BLEManager;
    [self.peripheral discoverServices:nil];
}

#pragma mark - Clear data
- (void)clearData {
    if (self.linkView) {
        [self.linkView removeFromSuperview];
    }
    if (self.peripheral) {
        //若已连接，则断开连接
        [self.centralManager cancelPeripheralConnection:self.peripheral];
    }
    if (self.BLEManager.delegate) {
        self.BLEManager.delegate = nil;
    }
    if (self.peripheral.delegate) {
        [self.BLEManager clear];
        self.peripheral.delegate = nil;
    }
}

#pragma mark 网络请求

#pragma mark - ---------- Actions ----------

#pragma mark - ---------- 协议方法 ----------

#pragma mark - CentralManger Delegate
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
    switch (central.state) {
        case CBCentralManagerStatePoweredOn:
            NSLog(@"\n 蓝牙已打开...");
            [self.centralManager scanForPeripheralsWithServices:nil options:nil];
            break;
        case CBCentralManagerStateUnknown:
            NSLog(@"\n 蓝牙状态未知...");
            break;
        case CBCentralManagerStatePoweredOff:
            NSLog(@"\n 蓝牙未打开...");
            break;
        case CBCentralManagerStateResetting:
            NSLog(@"\n 蓝牙初始化中...");
            break;
        case CBCentralManagerStateUnsupported:
            NSLog(@"\n 当前蓝牙不支持连接...");
            break;
        case CBCentralManagerStateUnauthorized:
            NSLog(@"\n 请进入设置->跑视界->开启蓝牙权限...");
            break;
        default:
            break;
    }
}

/**
 *  扫描蓝牙的代理
 *
 *  @param central           中心设备
 *  @param peripheral        扫描到的蓝牙
 *  @param advertisementData 在ios中蓝牙广播信息中通常会包含以下4种类型的信息。ios的蓝牙通信协议中不接受其他类型的广播信息。
 因此需要注意的是，如果需要在扫描设备时，通过蓝牙设备的Mac地址来唯一辨别设备，那么需要与蓝牙设备的硬件工程师沟通好：将所需要的Mac地址放到一下几种类型的广播信息中。
 通常放到kCBAdvDataManufacturerData这个字段中。
 kCBAdvDataIsConnectable = 1;
 kCBAdvDataLocalName = XXXXXX;
 kCBAdvDataManufacturerData = <XXXXXXXX>;
 kCBAdvDataTxPowerLevel = 0;
 *  @param RSSI              信号强度
 */
-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI{
    if (![self.devicesMArr containsObject:peripheral]) {
        NSLog(@"\n 发现外围设备:%@ \n RSSI:%@ \n advertisementData:%@", peripheral, RSSI, advertisementData);
        //        if ([peripheral.name hasPrefix:PERIPHERAL_PREFIX]) {
        [self.devicesMArr insertObject:peripheral atIndex:0];
        //        }
        self.linkView.dataSource = self.devicesMArr;
        [self.linkView reloadData];
    }
}

/**
 *  蓝牙连接成功时候的代理
 *
 *  @param central    中心设备
 *  @param peripheral 当前连接的设备
 */
-(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
    NSLog(@"\n 连接蓝牙'%@'成功...", peripheral.name);
    self.peripheral = peripheral;
    [self.centralManager stopScan];// 停止扫描外设
    [self.linkView indicatorAnimating:NO peripheral:peripheral];
    [self configPeripheral];
    WEAK(weakSelf);
    [UIView animateWithDuration:DURATION_LINKVIEW_ALPHA animations:^{
        [weakSelf.linkView setAlpha:.0f];
    } completion:^(BOOL finished) {
        [weakSelf.linkView setHidden:YES];
    }];
}

/**
 *  蓝牙链接失败的代理
 *
 *  @param central    中心设备
 *  @param peripheral 当前连接的外设
 *  @param error      错误信息
 */
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error {
    [self.linkView indicatorAnimating:NO peripheral:peripheral];
    NSLog(@"\n 连接蓝牙'%@'失败,\n Error info:%@", peripheral.name, [error localizedDescription]);
}

/**
 *  蓝牙断开连接的代理
 *
 *  @param central    中心设备
 *  @param peripheral 当前需要断开连接的外设
 *  @param error      错误信息
 */
-(void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
    NSLog(@"\n 蓝牙'%@'断开链接...", peripheral.name);
    [self.linkView setHidden:NO];
    [self.view bringSubviewToFront:self.linkView];
    WEAK(weakSelf);
    [UIView animateWithDuration:DURATION_LINKVIEW_ALPHA animations:^{
        [weakSelf.linkView setAlpha:1.0f];
    }];
    //重新连接
    if (!self.isDismiss) {
        [self.centralManager scanForPeripheralsWithServices:@[self.peripheralIdentifier] options:nil];
        [self connectPeripheralWithPeripheralIdentifier:self.peripheralIdentifier];
    }
}

#pragma mark - ||============ BLE Manager Delegate ============||
- (void)updateConnectStatus:(SYS_STATUS)status {
    switch (status) {
        case  STATUS_NORMAL: {
            NSLog(@"\n 待机状态...");
        }
            break;
        case STATUS_END: {
            NSLog(@"\n 减速已停机状态(还未返回到待机)");
        }
            break;
        case STATUS_START: {
            NSLog(@"\n 开始启动状态...");
        }
            break;
        case STATUS_RUNNING: {
            NSLog(@"\n 运行中状态...");
        }
            break;
        case STATUS_STOP: {
            NSLog(@"\n 减速停止中状态...");
        }
            break;
        case STATUS_ERROR: {
            NSLog(@"\n 跑步机处于故障状态...");
            [self clearData];
        }
            break;
        case STATUS_SAFETY: {
            NSLog(@"\n 跑步机处于安全锁状态...");
            [self clearData];
        }
            break;
        case STATUS_DISRUN: {
            NSLog(@"\n 跑步机处于睡眠状态，请尝试点击跑步机上的唤醒按钮以唤醒设备...");
            [self clearData];
        }
            break;
    }
}

- (void)countdown:(int)countdown {
    NSLog(@"\n 开始跑步倒计时:%d", countdown);
}

- (void)updateBLEDataWithModel:(HR_BLELinkInfoModel *)model {
    NSLog(@"\n Link info model info:%@", model);
}

#pragma mark - ---------- 公有方法 ----------

#pragma mark - ---------- 重写属性合成器 ----------

#pragma mark - ---------- 懒加载 ----------
- (NSMutableArray<CBPeripheral *> *)devicesMArr {
    if (!_devicesMArr) {
        _devicesMArr = [NSMutableArray array];
    }
    return _devicesMArr;
}

@end
